<?php

namespace Home\Controller;

use Utuo\ForegroundController;

class SeckillController extends ForegroundController {
	
	private $seckill = null;
	
	public function _init() {
		layout ( false );
		
		$this->seckill = M ( 'Seckill' )->where ( 'status=1 and is_deleted=0' )->find ();
	}
	
	public function indexAction() {
		$this->assign ( 'seckill', $this->seckill );
		$this->display ();
	}
	
	public function applyAction() {
		$now = time();
		if ( $now < $this->seckill['begin_time'] or $now < strtotime(date( 'Y-m-d' ).' '.$this->seckill['start_time']) ) {
			$this->ajaxError ( '亲，活动还未开始，再等一会哦！' );
		} elseif( !$this->seckill or $now > $this->seckill['end_time'] or $now > strtotime(date( 'Y-m-d' ).' '.$this->seckill['over_time'])) {
			$this->ajaxError ( '亲，活动已经结束，下次早点来哦！' );
		}
		
		$tel=I ( 'tel' );
		$isApply = $this->isApply($tel);
		if ($isApply === false) {
			$this->ajaxError ( '亲~网络有点忙，请再试一次吧！' );
		} else if(empty($isApply)){
			$m = D ( 'SeckillApply' );
			$m->name = I ( 'name' );
			$m->tel = $tel;
			$m->room_id = I ( 'room_id' );
			$m->apply_time = time ();
			$m->date=date("Y-m-d");
			$id = $m->add ();
			if($id === false){
				$this->ajaxError ( '亲~网络有点忙，请再试一次吧！' );
			} else {
				if ($this->getApplyCount ( $id ) >= $this->seckill['daily_number']) {
					D ( 'seckill_apply' )->where("id=%d",$id)->save(array('is_error'=>1));//超过人数后设置is_error=1表示为未成功
					$this->ajaxError ( '哎呀，太遗憾了！下次活动期待您的参与！' );
				} else {
					//$this->ajaxSuccess ( '请晚上再来参加活动（OK）' );
				$this->ajaxSuccess ( '恭喜你秒杀成功啦！我们工作人员会尽快与您联系送货。' );
				}
			}
		} else {
			if($isApply['is_error'] == 1){
				$this->ajaxError ( '亲~您已经参与过了哟！' );
			}
			$this->ajaxError ( '亲~WiFi虽小，可不要贪多哟！' );
		} 
	}
	
	public function getStartTimeAction() {
		$condation = array (
				'status' => 1,
				'is_deleted' => 0 
		);
		$seckill = M ( 'Seckill' )->where ( $condation )->find ();
		$seckill ['begin_time'] = date ( "Y/m/d H:i:s", $seckill ['begin_time'] );
		$seckill ['end_time'] = date ( "Y/m/d H:i:s", $seckill ['end_time'] );
		$seckill ['current_time'] = date ( 'Y/m/d H:i:s' ,time());
		$seckill ['current_date'] = date ( 'Y/m/d',time() );
		if($this->getApplyCount()>$this->seckill['daily_number'])
		{
		 $seckill['isbeyond']=1;	
		}else {
			$seckill['isbeyond']=0;
		}
		$this->ajaxReturn ( $seckill );
	}
	
	private function isApply($tel) {
		return M ( 'SeckillApply' )->where ( array(
			"tel" => $tel,
				"date" => date("Y-m-d")
		))->find ();
	}
	
	private function getApplyCount($id=null) {
		$preTime = floor ( time () / (24 * 3600) ) * (24 * 3600);
		$nestTime = (floor ( time () / (24 * 3600) ) + 1) * (24 * 3600);
		$condation['apply_time']=array(array('EGT',$preTime),array('ELT',$nestTime),'and');
		$id and $condation['id']=array(array('LT',$id));
		$count = M ( 'SeckillApply' )->where ( $condation )->count ();
		return $count;
	}

}